//
//  InstallationImageTableViewCell.swift
//  GreenDeal
//
//  Created by Moennig Q on 2/12/2022.
//
import UIKit
import SnapKit
import Alamofire
import SDWebImage
import PDFKit
class InstallationImageTableViewCell: UITableViewCell {

    lazy var seqNoLabel: BaseLabel = {
        let label = BaseLabel()
        
        label.textAlignment = .left
        label.textColor = UIColor(red: 0.25, green: 0.24, blue: 0.25,alpha:1)
        label.setFont(R.font.sfProTextRegular(size: 15))
        return label
    }()
    
    lazy var photoImageView: UIImageView = {
        let image = UIImageView()
        image.backgroundColor = .lightGray
        image.layer.cornerRadius = Constant.StandardCornerRadius
        image.clipsToBounds = true
        image.contentMode = .scaleAspectFit
        return image
    }()
    lazy var activityView: UIActivityIndicatorView = {
        let activityView = UIActivityIndicatorView()
        
        return activityView
    }()
    
    lazy var descripLabel: BaseLabel = {
        let label = BaseLabel()
        
        label.textAlignment = .left
        label.textColor = UIColor(red: 0.15, green: 0.13, blue: 0.14,alpha:1)
        label.setFont(R.font.sfProTextRegular(size: 15))
        label.numberOfLines = 0
        
        return label
    }()
    
    lazy var uploadFlagImageView: UIImageView = {
        let image = UIImageView()
        return image
    }()
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.initUI()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.initUI()
        
    }
    func initUI(){
        self.contentView.backgroundColor = .white
        
        //image
        self.contentView.addSubview(photoImageView)
        photoImageView.snp.makeConstraints { (make) in
            make.top.equalTo(12)
            make.left.equalTo(16)
            make.width.equalTo(65)
            make.height.equalTo(54)
            make.bottom.equalTo(-12)
        }
        
        // 停止后，隐藏菊花
        activityView.hidesWhenStopped = true
        //Style: whiteLarge比较大的白色环形进度条;white白色环形进度条;gray灰色环形进度条
        activityView.style = UIActivityIndicatorView.Style.white
        self.contentView.addSubview(activityView)
        activityView.snp.makeConstraints { (make) in
            make.center.equalTo(photoImageView)
        }
        //uploadFlagImageView,是否上传成功的标记，红色感叹号是本地数据没有上传，绿色勾表示上传成功
        self.addSubview(uploadFlagImageView)
        uploadFlagImageView.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(photoImageView)
            make.size.equalTo(CGSize(width: 16, height: 11))
        }
        //description
        descripLabel.numberOfLines = 0
        self.contentView.addSubview(descripLabel)
        descripLabel.snp.makeConstraints { (make) in
            make.left.equalTo(photoImageView.snp.right).offset(12)
            make.right.equalToSuperview().offset(-16)
            make.height.greaterThanOrEqualTo(0)
            make.centerY.equalToSuperview()
        }
        //line view
        let lineView = View(hexStr: Constant.SeparatorColorHexStr)
        self.contentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
    }
    
    func setData(_ model : CheckListImageDBModel, rowNumber: Int){
        self.seqNoLabel.text = "\(rowNumber)."
        self.descripLabel.text = model.title
        let imagePath = model.image
        if  imagePath.contains(APPConfig.PDFSuffix){//pdf
            if model.record_at != ""   {
                let convertDateTime = self.convertDateTimeStrWithoutSec(model.record_at)
                self.descripLabel.text = "Uploaded on: " + convertDateTime
            }
        }else{
            var convertDateTime: String = ""
            let photoCreatedAt = model.photo_created_at
            if photoCreatedAt.trimmingCharacters(in: .whitespaces) != ""{
                convertDateTime = self.convertDateTimeStrWithoutSec(photoCreatedAt)
                
            }else if model.record_at != ""  {
                convertDateTime = self.convertDateTimeStrWithoutSec(model.record_at)
            }
            if convertDateTime != ""{
                self.descripLabel.text = "Taken on: " + convertDateTime
            }
            
        }
        self.uploadFlagImageView.isHidden = false
        if imagePath.contains("http") {//来自服务器
            //
            self.uploadFlagImageView.image = UIImage(named: "UploadImageSuccess")
            guard let url = URL(string: imagePath) else {
                return
            }
            //此处不能判断是否有网络，因为没有网络的时候要用图片缓存
            if model.image.contains(APPConfig.PDFSuffix){
                self.photoImageView.image = UIImage(named: "installation_detail_checklist_pdf_icon")
//                    //来自网络缩略图
//                    self.activityView.startAnimating()
//                    self.pdfThumbnail(url) { image in
//                        self.activityView.stopAnimating()
//                        if let img = image {
//                            self.photoImageView.image = img
//                        }else{
//                            self.photoImageView.image = UIImage(named: "installation_detail_panelnumber_list_loadfaild")
//                        }
//                    }
            }else{
                self.activityView.startAnimating()
                self.photoImageView.sd_setImage(with: url, placeholderImage: UIImage(named: "installation_detail_panelnumber_list_loadfaild"), options: [SDWebImageOptions.scaleDownLargeImages]) { image, error, cashtype, url in
                    self.activityView.stopAnimating()
                }
            }
        }else{
            self.uploadFlagImageView.image = UIImage(named: "uploadImageFailed")
            if imagePath.contains(APPConfig.PDFSuffix){
                self.photoImageView.image = UIImage(named: "installation_detail_checklist_pdf_icon")
//                    //pdf本地缩略图
//                    self.pdfThumbnail(URL(fileURLWithPath: model.image!)) { image in
//                        if let img = image {
//                            self.photoImageView.image = img
//                        }
//                    }
            }else{
                if let image = UIImage(contentsOfFile: imagePath)  {
                    self.photoImageView.image = image.generateThumbnailImage()
                }
            }
        }
    }
    private func convertDateTimeStrWithoutSec(_ dateTimeStr: String)-> String{
        var resultStr = dateTimeStr
        let dm: DateFormatter = DateFormatter()
        dm.locale = Locale(identifier: "en_AU")
        dm.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        if let date = dm.date(from: dateTimeStr){
            dm.dateFormat = "MMM dd yyyy HH:mm('GMT'XXXXX)"
            resultStr = dm.string(from: date)
        }else {//兼容没有时区的老数据
            dm.dateFormat = "MMM dd yyyy HH:mm:ss.SSS"//毫秒必须是大写，格式才对
            if let date = dm.date(from: dateTimeStr){
                dm.dateFormat = "MMM dd yyyy HH:mm"
                resultStr = dm.string(from: date)
            }
        }
        return resultStr
    }
    // MARK: - 将PDF的第一页转换成100像素的缩略图图片
    private func pdfThumbnail(_ url: URL, width: CGFloat = 100, closure: @escaping ((UIImage?)->Void)){
//            guard let path = Bundle.main.path(forResource: "实例", ofType: "pdf") else { return nil}
//            let url = URL(fileURLWithPath: path)
        DispatchQueue.global().async {
            guard let data = try? Data(contentsOf: url),let pdfDoc = PDFDocument(data: data),
                  let page = pdfDoc.page(at: 0) else {
                DispatchQueue.main.async {
                    closure(nil)
                }
                
                return
            }
//            let pageCount = pdfDoc.pageCount
            let pageSize = page.bounds(for: .mediaBox)
            let pdfScale = width / pageSize.width// Apply if you're displaying the thumbnail on screen
            let scale = UIScreen.main.scale * pdfScale
            let screenSize = CGSize(width: pageSize.width * scale,
                                    height: pageSize.height * scale)
            let img = page.thumbnail(of: screenSize, for: .mediaBox)
            DispatchQueue.main.async {
                closure(img)
            }
        }
    }
}
